package com.sdkx.app.ViewModel;

import android.util.Log;

import com.sdkx.app.model.TrackPoint;

import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;

import java.util.ArrayList;
import java.util.List;

import cn.creable.gridgis.geometry.IEnvelope;
import cn.creable.gridgis.geometry.Point;

public class TrackPointManager extends LitePalSupport {
    /**
     * 新建航迹点
     * @param trackPoint
     * @return
     */
    public static boolean insert(TrackPoint trackPoint){
        if(trackPoint ==null)
            return false;
        return trackPoint.save();
    }

    public static void createIndex(){
        String indexinfo = "create index if not exists lineIndex_track on TrackPoint ( linetime )";
        LitePal.getDatabase().execSQL(indexinfo);
         indexinfo = "create index if not exists points_track on TrackPoint ( linetime,latitude,longitude )";
        LitePal.getDatabase().execSQL(indexinfo);
    }

    public static List<TrackPoint> getPointsByScreen(IEnvelope envelope){
        List<TrackPoint> list = new ArrayList<>();
        int count= 0;
        try {
            String slat = String.format(" linetime='1' and (latitude between %f and %f) and ",envelope.getYMin(),envelope.getYMax());  //bitthday between ? and ?
            String slon = String.format(" longitude between %f and %f",envelope.getXMin(),envelope.getXMax());
            long time = System.currentTimeMillis();
            count  = LitePal.where(slat+slon).count(TrackPoint.class);
            if(count > 0) {
                int div = count/20;
                if(div > 0) {
                    for (int i = 0; i < count; i += div) {
                        list.addAll(LitePal.where(slat + slon).offset(i).limit(1).find(TrackPoint.class));
                    }
                }else{
                    list.addAll(LitePal.where(slat + slon).find(TrackPoint.class));
                }
            }
            long res = System.currentTimeMillis()-time;
            Log.d("trackpoint","time = "+res);
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    public static List<TrackPoint> getAll(){
    return  LitePal.where(" linetime=1").find(TrackPoint.class);
}

    public static void insertdata(){
        Point start = new Point(116.156985, 40.065789);
        double length =111.1*Math.cos(start.getY()*Math.PI/180);
        double div = 0.08f/length;
        for(int i =0;i<12000;i++){
            TrackPoint trackPoint = new TrackPoint();
            trackPoint.setAltitude(1000);
            trackPoint.setAngle(20);
            trackPoint.setCreateTime(System.currentTimeMillis());
            trackPoint.setTrackLine(1);
            trackPoint.setSpeed(200);
            trackPoint.setLatitude(start.getY());
            trackPoint.setLongitude(start.getX());
            start.setX(start.getX()+div);
            trackPoint.save();
        }
    }
}
